'use strict'

import { app, BrowserWindow, Menu, Tray, nativeImage, dialog } from 'electron'
import '../renderer/store'

let mainWindow
let tray = ''
const bookURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:9080`
  : `file://${__dirname}/index.html`

const isMac = process.platform === 'darwin'
console.log(isMac)
// init 初始化方法
function init () {
  createTray()
  createBookWindow()
}
// 创建主窗口
function createBookWindow () {
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    height: 463, // 窗口宽度，默认是800
    width: 500, // 窗口高度，默认是600
    useContentSize: true, // 使用web网页size, 这意味着实际窗口的size应该包括窗口框架的size，稍微会大一点，默认为 false
    transparent: true, // 窗口 透明
    frame: true, // 将frame设为false会把标题和窗口控制按钮（红绿灯）全部隐藏
    webPreferences: {
      devTools: false, // devtool调试面板
      webSecurity: false // cors
    }
  })

  mainWindow.loadURL(bookURL)

  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

// 创建托盘菜单
function createTray () {
  const logo = `${__static}/mac.png`
  // 创建一个与 image 相关的 icon
  tray = new Tray(logo)
  const menuList = [
    {
      label: '小说模式',
      click () {
        // createBookWindow()
      }
    },
    {
      label: '关于',
      click () {
        const logo = `${__static}/mac.png`
        const image = nativeImage.createFromPath(logo)
        const options = {
          type: 'info',
          title: '关于',
          message: '小峰哥开发辅助工具\n\n版本：1.0.0\n\n作者：黄雪峰\n\n源码地址：https://gitee.com/xf_nodejs/underwork',
          buttons: ['确认'],
          icon: image
        }
        dialog.showMessageBox(options)
      }
    },
    {
      type: 'separator'
    },
    {
      accelerator: 'CommandOrControl+Alt+X',
      label: '退出',
      click () {
        Exit()
      }
    }
  ]
  // setContextMenu：为这个 icon 设置 context menu
  // buildFromTemplate
  tray.setContextMenu(Menu.buildFromTemplate(menuList))
}
function Exit () {
  app.quit()
}
// ready 启动
app.on('ready', init)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
  }
})

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}
/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

/*
import { autoUpdater } from 'electron-updater'

autoUpdater.on('update-downloaded', () => {
  autoUpdater.quitAndInstall()
})

app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
 */
